#include "WinFile.h"

WinFile::WinFile(const WinFile& a_File)
: m_File(a_File.m_File)
{

}

WinFile::WinFile(void)
: m_File((HANDLE)-1)
{
	_ASSERT(false);
}

WinFile::WinFile(HANDLE a_hFile)
: m_File(a_hFile)
{
}

WinFile WinFile::OpenReadOnly(const std::string& a_Path)
{
	HANDLE l_File = CreateFile(
						a_Path.c_str()
					,	GENERIC_READ
					,	FILE_SHARE_READ
					,	NULL
					,	OPEN_EXISTING
					,	FILE_ATTRIBUTE_NORMAL
					,	NULL
					);

	return WinFile(l_File);
}

WinFile WinFile::OpenReadWrite(const std::string& a_Path)
{
	HANDLE l_File = CreateFile(
						a_Path.c_str()
					,	GENERIC_READ | GENERIC_WRITE
					,	0
					,	NULL
					,	OPEN_EXISTING
					,	FILE_ATTRIBUTE_NORMAL
					,	NULL
					);

	return WinFile(l_File);
}

WinFile WinFile::Create(const std::string& a_Path)
{
	HANDLE l_File = CreateFile(
						a_Path.c_str()
					,	GENERIC_READ | GENERIC_WRITE
					,	0
					,	NULL
					,	CREATE_NEW
					,	FILE_ATTRIBUTE_NORMAL
					,	NULL
					);

	return WinFile(l_File);
}

WinFile WinFile::CreateTemp(const std::string& a_Path)
{
	HANDLE l_File = CreateFile(
						a_Path.c_str()
					,	GENERIC_READ | GENERIC_WRITE
					,	FILE_SHARE_DELETE
					,	NULL
					,	CREATE_NEW
					,	FILE_FLAG_DELETE_ON_CLOSE
					,	NULL
					);

	return WinFile(l_File);
}

void WinFile::Write(const std::string & a_Line)
{
	DWORD l_Written = 0;

	WriteFile(
		m_File
	,	a_Line.c_str()
	,	a_Line.size()
	,	&l_Written
	,	NULL
	);
}

std::string WinFile::Read()
{

	DWORD l_Read = 0;
	char l_Buffer[4096];
	ReadFile(
		m_File
	,	l_Buffer
	,	4096
	,	&l_Read
	,	NULL
	);

	return std::string(l_Buffer, l_Read);
}

WinFile::~WinFile(void)
{
	CloseHandle(m_File);
}
